<template>
  <scroll-view class="material-page">
    <view class="main-container">
      <!-- 用户基本资料区域 -->
      <view class="header-box">
        <!-- 返回按钮 -->
        <nav-bar title="个人资料" background="#3FD3D1" color="#ffffff" textAlign="center"> </nav-bar>
        <!-- 头像部分 -->
        <view class="header" @click="handleSwitchAvatar">
          <image class="avatar-image" :src="userAvatar" mode="aspectFill"></image>
          <image mode="widthFix" class="changeHeaderImg" src="/static/images/change_header.png" />
        </view>
        <!-- 昵称部分 -->
        <view class="userName">
          <view v-if="inputState=='userName'" style="height: 100%;">
            <input auto-focus="true" type="text" v-model.trim="editDataObj.userName" class="userNameInput"
              @blur="hideState" />
          </view>
          <view v-else class="userNameShow">
            <text>{{ editDataObj.userName }}</text>
            <uni-icons class="right-icon" custom-prefix="iconfont" type="icon-edit" color="#fff" size="28rpx"
              @click="showInput('userName')"></uni-icons>
          </view>
        </view>
        <!-- 个性签名部分 -->
        <view class="userSignature">
          <view v-if="inputState=='userSignature'" style="height: 100%;">
            <input auto-focus="true" type="text" v-model.trim="editDataObj.userSignature" class="userSignatureInput"
              @blur="hideState" />
          </view>
          <view v-else class="userSignatureShow">
            <text>{{ editDataObj.userSignature }}</text>
            <uni-icons class="right-icon" custom-prefix="iconfont" type="icon-edit" color="#fff" size="28rpx"
              @click="showInput('userSignature')"></uni-icons>
          </view>
        </view>
      </view>
      <!-- 圆弧部分 -->
      <view class="header-footer"></view>
      <!-- 内容区域 -->
      <view class="content">
        <!-- 用户ID -->
        <view class="contentItem">
          <view class="contentItemLeft">用户ID</view>
          <view class="contentItemRight">
            <text>{{ initDataObj.id }}</text>
          </view>
        </view>
        <!-- 用户性别 -->
        <view class="contentItem">
          <view class="contentItemLeft">性别</view>
          <picker class="picker-container" @change="upSelectSexConfirm" :value="pickerIndex" :range="sexList">
            <view class="picker-content">
              <text>{{sexList[editDataObj.userSex]}}</text>
              <view class="icon-container">
                <uni-icons class="icon-right" custom-prefix="iconfont" type="icon-back" color="#545454" size="28rpx">
                </uni-icons>
              </view>
            </view>
          </picker>
        </view>
        <!-- 用户手机号 -->
        <view class="contentItem">
          <view class="contentItemLeft">手机号</view>
          <view class="contentItemRight">
            <input v-if="inputState=='userPhone'" auto-focus="true" maxlength="11" type="number"
              v-model.trim="editDataObj.userPhone" class="userPhoneInput" @blur="hideState" />
            <view v-else class="contentItemRightView">
              <text>{{ editDataObj.userPhone }}</text>
              <view class="icon-container" @click="showInput('userPhone')">
                <uni-icons custom-prefix="iconfont" type="icon-edit" color="#666" size="28rpx" style="fontWeight: bold">
                </uni-icons>
              </view>
            </view>
          </view>
        </view>
        <!-- 用户微信号 -->
        <view class="contentItem">
          <view class="contentItemLeft">微信号</view>
          <view class="contentItemRight">
            <input v-if="inputState=='userWx'" auto-focus="true" maxlength="16" type="text"
              v-model.trim="editDataObj.userWx" class="userWxInput" @blur="hideState" />
            <view v-else class="contentItemRightView">
              <text>{{ editDataObj.userWx }}</text>
              <view class="icon-container" @click="showInput('userWx')">
                <uni-icons custom-prefix="iconfont" type="icon-edit" color="#666" size="28rpx" style="fontWeight: bold">
                </uni-icons>
              </view>
            </view>
          </view>
        </view>
        <!-- 保存按钮 -->
        <view class="saveBtn" @click="submitMaterial">保存</view>
      </view>
    </view>
  </scroll-view>
</template>

<script>
  import {
    HOST_URL
  } from "@/api/index.js";
  //11位手机号码正则验证
  let reg_tel = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  let reg_wx = /^[a-zA-Z][a-zA-Z\d_-]{5,19}$/;

  import {
    getUserInfoApi,
    putMaterialApi
  } from "@/api/my/material.js";
  export default {
    data() {
      return {
        pickerIndex: 0, // 默认选中项
        sexList: [
          // 性别选择列表
          "男",
          "女",
          "保密",
        ],
        // 状态
        inputState: '',
        // 修改的数据
        editDataObj: {
          // 修改的头像
          userAvatar: "/static/images/loginAvatar.png",
          // 修改的名称
          userName: "启嘉校园",
          // 修改的个性签名
          userSignature: "www.change.tm",
          // 修改的手机号
          userPhone: "",
          // 修改的微信号
          userWx: "",
          // 修改的性别
          userSex: 0,
        },
        // 初始数据
        initDataObj: {
          // 修改的头像
          userAvatar: "/static/images/loginAvatar.png",
          // 修改的名称
          userName: "启嘉校园",
          // 修改的个性签名
          userSignature: "www.change.tm",
          // 修改的手机号
          userPhone: "",
          // 修改的微信号
          userWx: "",
          // 修改的性别
          userSex: 0,
        },
      };
    },
    computed: {
      userAvatar() {
        return this.editDataObj.userAvatar ?
          this.editDataObj.userAvatar :
          '/static/images/defaultAvatar.jpg'
      }
    },
    onLoad() {
      this.getUserInfoObj();
    },
    methods: {
      // 返回上一页
      handleBack() {
        uni.navigateBack()
      },
      // 选择性别确认
      upSelectSexConfirm(event) {
        const {
          value
        } = event.detail;
        this.editDataObj.userSex = value;
      },
      // 显示
      showInput(type) {
        this.inputState = type;
      },
      // 隐藏
      hideState() {
        this.inputState = "";
      },
      // 获取个人资料数据
      async getUserInfoObj() {
        uni.showLoading({
          mask: true
        })
        const {
          data: result
        } = await getUserInfoApi();
        if (result.success) {
          let data = result.data.userInfo;
          this.editDataObj = {
            userAvatar: (data && data.avatar) || "",
            userName: (data && data.userName) || "",
            userSignature: (data && data.signature) || "",
            userPhone: (data && data.phoneNumber) || "",
            userWx: (data && data.wxNum) || "",
            userSex: (data && data.sex) || 0,
            id: (data && data.id) || "",
          };
          let obj = JSON.parse(JSON.stringify(this.editDataObj));
          this.$set(this, 'initDataObj', obj);
          this.isInitState = true;
        } else {
          uni.showToast({
            title: "网络异常，稍后重试！",
            icon: "none",
          });
        }
        uni.hideLoading()
      },
      // 保存
      async submitMaterial() {
        let initDataObj = Object.values(this.initDataObj);
        let editDataObj = Object.values(this.editDataObj);
        let isChange = false;
        for (let text = 0; text < initDataObj.length; text++) {
          if (initDataObj[text] != editDataObj[text]) {
            isChange = true;
            break;
          }
        }
        if (!isChange) {
          uni.showToast({
            title: "保存成功",
            icon: "none",
          });
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/my/my",
            });
          }, 800);
          return;
        }
        if (!reg_tel.test(this.editDataObj.userPhone) && this.editDataObj.userPhone != '') {
          uni.showToast({
            title: "请正确输入你的手机号",
            icon: "none",
          });
          return;
        }
        if (!reg_wx.test(this.editDataObj.userWx) && this.editDataObj.userWx != '') {
          uni.showToast({
            title: "请正确输入你的微信号",
            icon: "none",
          });
          return;
        }

        if (this.editDataObj.userName.length > 8) {
          uni.showToast({
            title: "你的昵称太长了，换一个吧~",
            icon: "none",
          });
          return;
        }
        if (this.editDataObj.userSignature.length > 60) {
          uni.showToast({
            title: "你的个签太长了，换一个吧~",
            icon: "none",
          });
          return;
        }
        const requestData = {
          avatar: this.editDataObj.userAvatar,
          userName: this.editDataObj.userName,
          signature: this.editDataObj.userSignature,
          phoneNumber: this.editDataObj.userPhone,
          wxNum: this.editDataObj.userWx,
          sex: this.editDataObj.userSex,
        };
        const {
          data: result
        } = await putMaterialApi(requestData);
        if (result.success) {
          this.initDataObj = JSON.parse(
            JSON.stringify(this.editDataObj)
          );
          uni.showToast({
            title: "保存成功",
            icon: "none",
          });
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/my/my",
            });
          }, 800);
        } else {
          uni.showToast({
            title: result.message,
            icon: "none",
          });
        }

      },
      // 更换头像
      handleSwitchAvatar() {
        // 微信小程序从基础库 2.21.0 开始， wx.chooseImage 停止维护，请使用 uni.chooseMedia 代替。
        // https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage
        let func = null;
        // #ifdef H5
        func = uni.chooseImage;
        // #endif
        // #ifdef MP-WEIXIN  
        func = uni.chooseMedia;
        // #endif
        console.log(func);
        func({
          count: 1,
          mediaType: ["image"],
          sourceType: ["album", "camera"],
          maxDuration: 30,
          camera: ["back", "front"],
          success: res => {
            console.log(res);
            const uploadFileSize = Math.floor(
              res.tempFiles[0].size / 1024 / 1024
            );
            if (uploadFileSize < 9) {
              let path = res.tempFiles[0].tempFilePath ?? res.tempFiles[0].path;
              this.uploadAvatar(path);
            } else {
              uni.showToast({
                title: "不得超过10MB",
                icon: "none",
              });
            }
          },
        });
      },
      // 上传头像
      async uploadAvatar(path) {
        console.log(path);
        uni.showToast({
          icon: "loading",
          title: "正在上传",
        });
        // 因h5 与 微信小程序使用的不同的的api选择图片 
        uni.uploadFile({
          url: HOST_URL + "/user/uploadFile",
          filePath: path,
          name: "file",
          header: {
            // "Content-Type": "multipart/form-data",
            token: getApp().globalData.getUser().token,
          },
          success: async res => {
            if (res.statusCode === 200) {
              const fileData = JSON.parse(res.data);
              if (fileData.code === 200) {
                this.editDataObj.userAvatar = fileData.data.url;
              }
            } else {
              uni.showToast({
                title: "上传失败",
                icon: "none",
              });
            }
          },
          fail: error => {
            uni.showToast({
              title: "上传失败",
              icon: "none",
            });
          },
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .material-page {
    height: 100vh;
    width: 100%;
  }

  .main-container {
    min-height: 100vh;
    width: 100%;
    background: #ffffff;

    // 用户头像信息区域
    .header-box {
      width: 100%;
      background: #3fd3d1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      align-items: center;

      // 返回容器
      .back-container {
        width: 100%;
        position: relative;
        z-index: 999;

        // 导航容器
        .nav-container {
          width: 100%;
          display: flex;
          align-items: center;
          position: fixed;
          left: 0;
          top: 0;
          box-sizing: border-box;

          .icon-container {
            padding-left: 20rpx;
            padding-right: 12rpx;
            box-sizing: border-box;
          }

          .title {
            font-size: 36rpx;
          }

        }
      }


      // 头像
      .header {
        width: 260rpx;
        height: 260rpx;
        margin-top: 40rpx;
        position: relative;

        .avatar-image {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }

        .mask {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
          background-color: rgba(0, 0, 0, 0.3);
          border-radius: 50%;
          overflow: hidden;
        }

        .changeHeaderImg {
          width: 60rpx;
          height: 60rpx;
          position: absolute;
          right: 0;
          bottom: 0;
          // transform: translateX(-50%) translateY(-50%);
        }
      }

      // 名称
      .userName {
        height: 36rpx;
        margin-top: 48rpx;
        width: 50%;
        font-family: SourceHanSansCN-Medium;

        .right-icon {
          margin-left: 16rpx;
        }

        .userNameInput {
          line-height: 36rpx;
          color: white;
          font-size: 36rpx;
          font-weight: 500;
          height: 100%;
          width: 100%;
          text-align: center;
        }

        .userNameShow {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;

          text {
            display: block;
            max-width: 100%;
            font-size: 36rpx;
            font-weight: 500;
            color: white;
            line-height: 36rpx;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }

      // 个性签名
      .userSignature {
        width: 60%;
        height: 40rpx;
        margin-top: 32rpx;
        font-family: SourceHanSansCN-Medium;

        .right-icon {
          margin-left: 16rpx;
        }

        .userSignatureInput {
          color: white;
          line-height: 40rpx;
          font-size: 28rpx;
          width: 100%;
          text-align: center;
          height: 40rpx;
          min-height: 40rpx;
        }

        .userSignatureShow {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100%;
          width: 100%;

          text {
            display: block;
            max-width: 100%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 28rpx;
            color: white;
            line-height: 40rpx;
            text-align: center;
          }
        }
      }
    }

    // 弧状部分
    .header-footer {
      width: calc(100% + 90rpx);
      height: 64rpx;
      // height: 40rpx;
      transform: translateX(-45rpx);
      background: #3FD3D1;
      border-bottom-right-radius: 375rpx 40rpx;
      border-bottom-left-radius: 375rpx 40rpx;
    }

    // 用户扩展资料区域
    .content {

      padding: 40rpx 32rpx 0rpx;
      box-sizing: border-box;
      $-height: 88rpx;

      .contentItem {
        width: 100%;
        height: $-height;
        display: flex;
        align-items: center;

        .contentItemLeft {
          width: 140rpx;
          color: #545454;
          font-size: 28rpx;
        }

        .contentItemRight {
          width: calc(100% - 140rpx);
          display: flex;
          justify-content: space-between;
          align-items: center;

          text {
            font-size: 28rpx;
            color: #333333;
          }

          .contentItemRightView {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
        }

        .picker-container {
          width: calc(100% - 140rpx);
          height: 100%;

          .picker-content {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #333333;
          }
        }

        .icon-container {
          padding: 0px 16rpx;
          height: $-height;
          line-height: $-height;

          .icon-right {
            display: inline-block;
            transform: rotateZ(180deg);
          }
        }

        .userPhoneInput,
        .userWxInput {
          color: #333333;
          line-height: $-height;
          font-size: 28rpx;
          height: 100%;
          width: 100%;
        }


      }

      // 保存按钮
      .saveBtn {
        margin: 120rpx 0rpx 80rpx;
        height: 96rpx;
        background: #3fd3d1;
        color: #ffffff;
        font-size: 32rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 8rpx;
      }
    }
  }
</style>